<template>
  <div>
    <div class="background"></div>
    <div class="saveMain">
      <div class="close" @touchend="close">
        <div class="icon"></div>
      </div>
      <div class="produce" :style="produceStyle">
        <div class="produceImagery" v-for="imagery in produce.content[0].imagery" :key="imagery.produceEryId"
          :style="imageryStyle(imagery)"> </div>
        <div class="produceRole" v-for="role in produce.content[0].role" :key="role.produceRoleId+999"
          :style="roleStyle(role)"> </div>
      </div>
      <div class="border"></div>
      <div class="title">给你的绘本取个名字吧</div>
      <input class="nameInput" v-model="picbookName" onblur="this.placeholder='点击输入绘本名称'" onfocus="this.placeholder=''"
        maxlength="7" placeholder="点击输入绘本名称" />
      <div class="save" @touchend="isPress?null:save()">保存</div>
      <div class="upload" @touchend="isPress?null:upload()">发布</div>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapActions } from "vuex"
export default {
  data() {
    return {
      picbookName: "",
      isPress: false
    }
  },
  computed: {
    produceStyle() {
      const background = this.produce.content[0].scene ? this.produce.content[0].scene : this.variable.STATICE_URLTITLE + "produce/默认场景.png"
      return {
        background: "url(" + background + ")0 0/100% 100%"
      }
    },
    imageryStyle(imagery) {
      return function (imagery) {
        return {
          background: "url(" + imagery.eryImgInWorld + ")0 0/100% 100%",
          width: imagery.widthInWorld,
          height: imagery.heightInWorld,
          top: imagery.topInWorld,
          left: imagery.leftInWorld
        }
      }
    },
    roleStyle(role) {
      return function (role) {
        return {
          background: "url(" + role.imageUrl + ")0 0/100% 100%",
          width: role.width,
          height: role.height,
          top: role.topInWorld,
          left: role.leftInWorld
        }
      }
    },
    ...mapGetters("produceStatus", {
      produce: "getProduce",
      userProduceList: "getUserProduceList"
    }),
    ...mapGetters("personalStatus", {
      userInformation: "getUserInformation"
    })
  },
  methods: {
    close: function () {
      this.$emit('saveTouch')
    },
    //检查
    check: function () {
      //过滤没有意象角色场景的创作页
      const produce = JSON.parse(JSON.stringify(this.produce))
      produce.content = this.produce.content.filter(item => { return item.imagery.length > 0 || item.role.length > 0 || item.scene })
      if (produce.content.length === 0) {
        this.setPopup({ content: "你还没有进行创作" })
        this.$emit('saveTouch')
        return
      }
      else {
        if (this.picbookName) {
          return produce
        }
        else {
          this.setPopup({ content: "请输入绘本名" })
          return
        }
      }
    },
    //保存
    save: async function () {
      this.clickMusic()
      this.isPress = true
      const produce = this.check()
      if (!produce) return
      //isRelease 未发布
      produce.detail.isRelease = false
      produce.detail.picbookName = this.picbookName
      const userProduceList = [...this.userProduceList] //复制一份用户创作列表
      //produceId不为0则修改对应的创作
      if (produce.detail.produceId >= 0) {
        for (let i = 0, len = userProduceList.length; i < len; i++) {
          if (userProduceList[i].detail.produceId === produce.detail.produceId) {
            userProduceList[i] = produce
            break
          }
        }
      }
      //新增创作 设置produceId
      else {
        produce.detail.produceId = 0
        if (userProduceList.length > 0) {
          produce.detail.produceId = Math.max.apply(Math, userProduceList.map(function (o) { return o.detail.produceId + 1 }))
        }
        userProduceList.push(produce)
      }
      const json = {
        deviceUuid: this.deviceUuid,
        key: "userProduceList",
        value: userProduceList
      }
      const [data, err] = await this.awaitWarp(this.$post(this.api.saveUserDate, json))
      if (err) {
        this.setPopup({ content: "保存失败-请检查网络" })
      }
      else {
        console.log(produce)
        console.log(userProduceList)
        this.setPopup({ content: "保存成功" })
        this.$emit('saveTouch')
        this.setUserProduceList(userProduceList) //修改用户创作列表
        this.clearProduce()  //清空创作面板
        this.$emit('reload')
      }
    },
    //发布
    upload: async function () {
      this.clickMusic()
      this.isPress = true
      const produce = this.check()
      if (!produce) return
      //isRelease 发布
      produce.detail.isRelease = true
      produce.detail.picbookname = this.picbookName
      produce.detail.nickname = this.userInformation.detail.nickname
      produce.detail.deviceUuid = this.deviceUuid
      const userProduceList = [...this.userProduceList] //复制一份用户创作列表
      //produceId不为0则修改对应的创作
      if (produce.detail.produceId >= 0) {
        for (let i = 0, len = userProduceList.length; i < len; i++) {
          if (userProduceList[i].detail.produceId === produce.detail.produceId) {
            userProduceList[i] = produce
            break
          }
        }
      }
      //新增创作 设置produceId
      else {
        produce.detail.produceId = 0
        if (userProduceList.length > 0) {
          produce.detail.produceId = Math.max.apply(Math, userProduceList.map(function (o) { return o.detail.produceId + 1 }))
        }
        userProduceList.push(produce)
      }
      const json = {
        deviceUuid: this.deviceUuid,
        key: "userProduceList",
        value: userProduceList
      }
      const [data, err] = await this.awaitWarp(this.$post(this.api.saveUserDate, json))
      if (err) {
        this.setPopup({ content: "保存失败-请检查网络" })
        return
      }
      this.eachDescendentParameters({
        object: produce,
        onEach: (map, key, value) => {
          if (typeof value === 'string' && (value.indexOf("nomedia") > -1) && (value.indexOf(".png") > -1 || value.indexOf(".jpg") > -1)) {
            try {
              value = "https://hz-huibenxia.oss-cn-shenzhen.aliyuncs.com" + value.match(/nomedia(\S*)/)[1]
            } catch (error) {
              console.log(error)
            }
            map[key] = value
          }
        }
      })
      delete produce.detail.produceId
      const json2 = {
        deviceUuid: this.deviceUuid,
        content: JSON.stringify(produce)
      }
      const [data2, err2] = await this.awaitWarp(this.$post(this.api.addPicbook, json2))
      if (err2) {
        this.setPopup({ content: "上传失败-请检查网络" })
        return
      }
      this.setPopup({
        content: "发布成功",
        callback: () => {
          this.setLoading({
            callback: () => {
              this.$router.push({ path: "/community" })
            }
          })
        }
      })
      console.log(produce)
      console.log(userProduceList)
      this.$emit('saveTouch')
      this.setUserProduceList(userProduceList) //修改用户创作列表
      this.clearProduce()  //清空创作面板
      this.$emit('reload')
    },
    ...mapActions("mainStatus", ["setPopup", "setLoading"]),
    ...mapActions("produceStatus", ["clearProduce", "setUserProduceList", "setCommunityList"])
  }
}
</script>
<style lang="stylus" scoped>
.background
  position absolute
  width 100%
  height 100%
  background rgba(0, 0, 0, 0.4)
  z-index 101
.saveMain
  background url($urlTitle + 'produce/上传背景.png') 0 0 / 100% 100%
  $coord('WHLT', 65vh, 75vh, 50%, 50%)
  transform translate3d(-50%, -50%, 0)
  z-index 101
  .close
    background url($urlTitle + 'icon/关闭背景.png') 0 0 / 100% 100%
    $coord('WHRT', 10vh, 7vh, -9vh, 7vh)
    .icon
      background url($urlTitle + 'icon/关闭.png') 0 0 / 100% 100%
      $coord('WHLT', 4vh, 4vh, 50%, 50%)
      transform translate3d(-65%, -50%, 0)
  .produce
    $coord('WHLT', 52vh, 28.4vh, 10%, 6.5vh)
    border 1vh solid white
    box-shadow 0px 0px 0.5rem rgba(0, 0, 0, 0.2)
    box-sizing border-box
    overflow hidden
    .produceImagery
      position absolute
    .produceRole
      position absolute
  .border
    background url($urlTitle + 'produce/上传装饰.png') 0 0 / 100% 100%
    $coord('WHLT', 52vh, 28.4vh, 10%, 6.5vh)
    pointer-events none
  .title
    font-size 3.5vh
    margin-top 62%
    color rgb(253, 152, 30)
  .nameInput
    margin-top 5%
    color rgb(253, 152, 30)
    background rgb(253, 226, 182)
    height 8vh
    width 50%
    border none
    outline none
    font-size 3vh
    border-radius 5vh
    box-sizing border-box
    text-align center
  input::-webkit-input-placeholder
    color rgb(253, 152, 30)
  .save
    background url($urlTitle + 'icon/按钮-黄.png') 0 0 / 100% 100%
    $coord('WHLB', 15.5vh, 7vh, 15vh, 8vh)
    color white
    font-size 3.5vh
    $alignCenter()
  .upload
    background url($urlTitle + 'icon/按钮-橙.png') 0 0 / 100% 100%
    $coord('WHRB', 15.5vh, 7vh, 15vh, 8vh)
    color white
    font-size 3.5vh
    $alignCenter()
</style>